{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solving an electric circuit using Particle Swarm Optimization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "PSO can be utilized in a wide variety of fields. In this example, the problem consists of analysing a given electric circuit and finding the electric current that flows through it. To accomplish this, the ```pyswarms``` library will be used to solve a non-linear equation by restructuring it as an optimization problem. The circuit is composed by a source, a resistor and a diode, as shown below.\n",
    "\n",
    "![Circuit](https://user-images.githubusercontent.com/39431903/43938822-29aaf9b8-9c66-11e8-8e54-01530db005c6.png)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mathematical Formulation\n",
    "\n",
    "Kirchhoff's voltage law states that the directed sum of the voltages around any closed loop is zero. In other words, the sum of the voltages of the passive elements must be equal to the sum of the voltages of the active elements, as expressed by the following equation:\n",
    "\n",
    "$U = v_D + v_R $, where $U$ represents the voltage of the source and, $v_D$ and $v_R$ represent the voltage of the diode and the resistor, respectively.\n",
    "\n",
    "To determine the current flowing through the circuit, $v_D$ and $v_R$ need to be defined as functions of $I$. A simplified Shockley equation will be used to formulate the current-voltage characteristic function of the diode. This function relates the current that flows through the diode with the voltage across it. Both $I_s$ and $v_T$ are known properties.\n",
    "\n",
    "$I = I_s  e^{\\frac{v_D}{v_T}}$\n",
    "\n",
    "Where:\n",
    "\n",
    "- $I$ : diode current\n",
    "- $I_s$ : reverse bias saturation current\n",
    "- $v_D$ : diode voltage\n",
    "- $v_T$ : thermal voltage\n",
    "\n",
    "Which can be formulated over $v_D$:\n",
    "\n",
    "$v_D = v_T \\log{\\left |\\frac{I}{I_s}\\right |}$\n",
    "\n",
    "The voltage over the resistor can be written as a function of the resistor's resistance $R$ and the current $I$:\n",
    "\n",
    "$v_R = R  I$\n",
    "\n",
    "And by replacing these expressions on the Kirschhoff's voltage law equation, the following equation is obtained:\n",
    "\n",
    "$U = v_T \\log{\\left |\\frac{I}{I_s}\\right |} + R I$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To find the solution of the problem, the previous equation needs to be solved for $I$, which is the same as finding $I$ such that the cost function $c$ equals zero, as shown below. By doing this, solving for $I$ is restructured as a minimization problem. The absolute value is necessary because we don't want to obtain negative currents.\n",
    "\n",
    "$c = \\left | U - v_T \\log{\\left | \\frac{I}{I_s} \\right |} - RI \\right |$\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Known parameter values\n",
    "\n",
    "The voltage of the source is $10 \\space V$ and the resistance of the resistor is $100 \\space \\Omega$. The diode is a silicon diode and it is assumed to be at room temperature.\n",
    "\n",
    "$U = 10 \\space V$\n",
    "\n",
    "$R = 100 \\space \\Omega$\n",
    "\n",
    "$I_s = 9.4 \\space pA = 9.4 \\times 10^{-12} \\space A$ (reverse bias saturation current of silicon diodes at room temperature, $T=300 \\space K$)\n",
    "\n",
    "$v_T = 25.85 \\space mV = 25.85 \\times 10^{-3} \\space V$ (thermal voltage at room temperature, $T=300 \\space K$)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Optimization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import modules\n",
    "import sys\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Import PySwarms\n",
    "import pyswarms as ps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on Python version: 3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34) \n",
      "[GCC 7.3.0]\n"
     ]
    }
   ],
   "source": [
    "print('Running on Python version: {}'.format(sys.version))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Defining the cost fuction\n",
    "\n",
    "The first argument of the cost function is a ```numpy.ndarray```. Each dimension of this array represents an unknown variable. In this problem, the unknown variable is just $I$, thus the first argument is a unidimensional array. As default, the thermal voltage is assumed to be $25.85 \\space mV$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cost_function(I):\n",
    "    \n",
    "    #Fixed parameters\n",
    "    U = 10\n",
    "    R = 100\n",
    "    I_s = 9.4e-12\n",
    "    v_t = 25.85e-3\n",
    "    \n",
    "    c = abs(U - v_t * np.log(abs(I[:, 0] / I_s)) - R * I[:, 0])\n",
    "    \n",
    "    return c  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setting the optimizer\n",
    "\n",
    "To solve this problem, the global-best optimizer is going to be used. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2019-05-18 15:41:35,474 - pyswarms.single.global_best - INFO - Optimize for 30 iters with {'c1': 0.5, 'c2': 0.3, 'w': 0.3}\n",
      "pyswarms.single.global_best: 100%|██████████|30/30, best_cost=14 \n",
      "2019-05-18 15:41:35,863 - pyswarms.single.global_best - INFO - Optimization finished | best cost: 14.045352861989468, best pos: [0.23426529]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 111 ms, sys: 12.1 ms, total: 123 ms\n",
      "Wall time: 411 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Set-up hyperparameters\n",
    "options = {'c1': 0.5, 'c2': 0.3, 'w':0.3}\n",
    "\n",
    "# Call instance of PSO\n",
    "optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=1, options=options)\n",
    "\n",
    "# Perform optimization\n",
    "cost, pos = optimizer.optimize(cost_function, iters=30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.23426529444241187\n"
     ]
    }
   ],
   "source": [
    "print(pos[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "14.045352861989468\n"
     ]
    }
   ],
   "source": [
    "print(cost)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Checking the solution\n",
    "\n",
    "The current flowing through the circuit is approximately $0.094 \\space A$ which yields a cost of almost zero. The graph below illustrates the relationship between the cost $c$ and the current $I$. As shown, the cost reaches its minimum value of zero when $I$ is somewhere close to $0.09$.\n",
    "\n",
    "The use of ```reshape(100, 1)``` is required since ```np.linspace(0.001, 0.1, 100)``` returns an array with shape ```(100,)``` and first argument of the cost function must be a unidimensional array, that is, an array with shape ```(100, 1)```. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEKCAYAAAARnO4WAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAIABJREFUeJzt3Xl4VOXZx/HvnZ0l7AFkkYCgbAJilCUhti4soiIKuCOoiIpAaKutrW211bdW+0rABRXFXRFBBESIVq0Ji0DYCfsOguzIvj/vHxl8KQoEkjNnJvP7XFcuZjkz535I+OXwzDn3Y845RESk+IvyuwAREQkOBb6ISIRQ4IuIRAgFvohIhFDgi4hECAW+iEiEUOCLiEQIBb6ISIRQ4IuIRIgYvws4UaVKlVxycrLfZYiIhI2ZM2dudc4lFWTbkAr85ORkcnNz/S5DRCRsmNmagm6rKR0RkQihwBcRiRAKfBGRCKHAFxGJEAp8EZEIocAXEYkQCnwRkQhRLAJ/8FfLWPD9j36XISIS0sI+8HfsPcSH09fS5ZUpjJnzvd/liIiErLAP/PKl4hj7c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lAl1M8d4T/nqI8eZ3Xvae5HwW0cs7tP3GDwC+AExeSOUoR/Zsxs4rAlUBjM3PkL4XnzOxRpwZX4hHN4Us4+RqIN7Nexx8ws8vM7ApgDflH6fFmVha46ize9wvgp176ZnamqZrd5E/xFEYX4B3nXC3nXLJzrib57W/TCvm+IqekwJewETjy7QxcEzgtM4/81sgbnHPrgBHkL/D9PjD7LN66H5BiZvPMbCHwwBnq2AZMNrMFhfjQ9jbyzzg60SjyF/sQ8YTaI4sEgZklA5855xqfxWv2OOdKe1aURBwd4YsEx1Gg7MkXXv2S4xdeAZu8L0siiY7wRUQihI7wRUQihAJfRCRCKPBFRCKEAl9EJEIo8EVEIsT/AY8vwmT9ZDt5AAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "x = np.linspace(0.001, 0.1, 100).reshape(100, 1)\n",
    "y = cost_function(x)\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.xlabel('Current I [A]')\n",
    "plt.ylabel('Cost');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another way of solving non-linear equations is by using non-linear solvers implemented in libraries such as ```scipy```. There are different solvers that one can choose which correspond to different numerical methods. We are going to use ```fsolve```, which is a general non-linear solver that finds the root of a given function. \n",
    "\n",
    "Unlike ```pyswarms```, the function (in this case, the cost function) to be used in ```fsolve``` must have as first argument a single value. Moreover, numerical methods need an initial guess for the solution, which can be made from the graph above. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import non-linear solver\n",
    "from scipy.optimize import fsolve"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.09404768643017938\n"
     ]
    }
   ],
   "source": [
    "c = lambda I: abs(10 - 25.85e-3 * np.log(abs(I / 9.4e-12)) - 100 * I)\n",
    "\n",
    "initial_guess = 0.09\n",
    "\n",
    "current_I = fsolve(func=c, x0=initial_guess)\n",
    "\n",
    "print(current_I[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The best solution value found using the PSO method was approximately the same as the one found using a non-linear solver, about $0.094 \\space A$. In fact, the relative error was less than $1 \\times 10^{-5}$."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
